<?php

namespace App\Listeners;


use App\Events\AppointEvent;
use App\Events\Event;
use App\Events\ScheduleEvent;
use App\Model\Business\ClasseStuden;
use App\Model\Business\ScheduleStuden;
use App\Model\Eeoapi\Eeocourse;
use App\Model\Eeoapi\Eeoteacher;
use App\Model\Foundation\Teacher;



class ScheduleListener extends  Listener
{
    /**
     * @param ScheduleEvent $event
     */
    public function handle(ScheduleEvent $event)
    {
        switch($event->action)
        {
            case Event::CREATE:
		    if(env('ASYN_MODE')){
                    $ss = ScheduleStuden::where('scheduleid',$event->scheduleid)
                        ->where('identity',1)
                        ->first();
                    $classeid = Eeocourse::where('eeocourseid',$event->courseId)
                        ->first();
                    $classeid = $classeid->chimpid;
                    $cs = ClasseStuden::where('classeid',$classeid)
                        ->where('identity',1)
                        ->first();
                    if($ss || $cs || $event->classId){
                        $this->create($event);
                    }
                }else{
                    $this->create($event);
                }
                break;
            case Event::UPDATE:
                if($event->classId){
                    $this->update($event);
                }
                break;
            case Event::LIVE:
                if($event->classId){
                    $this->modifyReplay($event);
                }
                break;
            case Event::DELETE:
                if($event->classId) {
                    $this->delete($event);
                }
                break;
            case Event::STUDENT:

                if($event->classId){
                    $this->student($event);
                }else{
                    $this->syncdata($event);
                }
                break;
            default: break;

        }
    }

    /**
     * 创建课节
     * @param ScheduleEvent $event
     */
    function create(ScheduleEvent $event)
    {
        try{
            $this->addTeacher($event->teacherAccount,$event->teacherName,$event->Filedata);
            $this->setUri('addCourseClass');
            $data = $this->dataMaker();
            $data["courseId"] = $event->courseId;
            $data["className"] = $event->className;
            $data["beginTime"] = $event->beginTime;
            $data["endTime"] = $event->endTime;
            $data["teacherAccount"] = $event->teacherAccount;
            $data["teacherName"] = $event->teacherName;
            $data["folderId"] = $event->folderId;
            $data["seatNum"] = $event->seatNum;
            $data["record"] = $event->record;
            $data["live"] = $event->live;
            $data["replay"] = $event->replay;

            $this->setRequest($data);
            $result = $this->callEeoApi();

            if($result['error_info']['errno'] === 1 || $result['error_info']['errno'] === 281) {
                $event->setClassID($result['data']);
                $this->getWebcast($event,$data["courseId"],$result['data']);
            }else{
                throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
            }
        }catch (\Exception $e){
            throw $e;
        }
    }

    /**
     * 修改课节
     * @param ScheduleEvent $event
     */
    function update(ScheduleEvent $event)
    {
        try{
            $this->setUri('editCourseClass');
            $data = $this->dataMaker();
            $data["courseId"] = $event->courseId;
            $data["classId"] = $event->classId;
            $data["className"] = $event->className;
            $data["beginTime"] = $event->beginTime;
            $data["endTime"] = $event->endTime;
            $data["teacherAccount"] = $event->teacherAccount;
            $data["teacherName"] = $event->teacherName;
            $data["folderId"] = $event->folderId;
            $data["record"] = $event->record;
            $data["live"] = $event->live;
            $data["replay"] = $event->replay;
            $this->setRequest($data);
            $result = $this->callEeoApi();

            if($result['error_info']['errno'] <> 1 ) {
                throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
            }
        }catch (\Exception $e){
            throw $e;
        }
    }

    function delete(ScheduleEvent $event)
    {
        try{
            if($event->courseId&&$event->classId){
                $this->setUri('delCourseClass');
                $data = $this->dataMaker();
                $data["courseId"] = $event->courseId;
                $data["classId"] = $event->classId;
                $this->setRequest($data);
                $result = $this->callEeoApi();

                if ($result['error_info']['errno'] == 1 || $result['error_info']['errno'] == 212) {
                    $event->delClassID();
                } else {
                    throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
                }
            }
        }catch (\Exception $e){
            throw $e;
        }
    }

    /**
     * 课节下添加/删除学生
     * @param $event
     */
    protected function student(ScheduleEvent $event)
    {
        try{
            $olds = $event->getStudents(true);
            $news = $event->getStudents();
            $data = $this->dataMaker();
            $data["courseId"] = $event->courseId;
            $data["classId"] = $event->classId;

            if(!empty($olds)){
                $myOlds=[];
                $this->setUri('delClassStudentMultiple');
                foreach ($olds as $old) {
                    $myOlds[] = $old['studentAccount'];
                }
                $data['studentJson'] = json_encode($myOlds);
                $data["identity"] = 1;
                $this->setRequest($data);
                $result = $this->callEeoApi();

                $code = $result['error_info']['errno'];
                if(!in_array($code,[1])){
                    throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
                }
            }

            if(!empty($news)){
                $myNews = [];
                $org = Event::getOrg();
                $this->setUri('addClassStudentMultiple');
                foreach ($news as $new) {
                    $myNew = [];
                    $myNew['account'] = $new['studentAccount'];
                    $myNew['name'] = $new['studentName'];
                    $myNew['password'] = $org['registerDefaultPwd'];
                    $myNews[] = $myNew;
                }
                $data['studentJson'] = json_encode($myNews);
                $data["isRegister"] = 1;
                $data["identity"] = 1;
                $this->setRequest($data);

                $result = $this->callEeoApi();
                $code = $result['error_info']['errno'];
                if(!in_array($code,[1])){
                    throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
                }
            }
        }catch (\Exception $e){
            throw $e;
        }
    }
    
    /**
     * 注册并添加老师到机构
     * @param
     * @throws \Exception
     */
    protected function addTeacher($teacherAccount,$teacherName,$Filedata,$password = null)
    {
        try{
//            $this->register($teacherAccount,$teacherName,$password);
            $this->setUri('addTeacher');
            $cfile = $this->uploadCheck($Filedata);
            $data = $this->dataMaker();
            $data["teacherAccount"] = $teacherAccount;
            $data["teacherName"] = $teacherName;
            $data["Filedata"] = $cfile;
            $this->setRequest($data);
            $result = $this->callEeoApi();

            $code = $result['error_info']['errno'] ;
            if(in_array($code,[1,133])) {
                $teacher = Teacher::where('ClassInNo',$teacherAccount)->first();
                $fileds = ['teacheruid'=>$teacher->teacheruid, 'stid'=>$result['data']];
                Eeoteacher::updateOrCreate($fileds);
            }else{
                throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
            }
        }catch (\Exception $e){
            throw $e;
        }

    }

    /**
     * 异步模式添加课节下学生创建数据
     *
     */
    protected function syncdata(ScheduleEvent $event)
    {
        try{
            ## 创建课节
            $this->addTeacher($event->teacherAccount,$event->teacherName,$event->Filedata);

            $this->setUri('addCourseClass');
            $data = $this->dataMaker();
            $data["courseId"] = $event->courseId;
            $data["className"] = $event->className;
            $data["beginTime"] = $event->beginTime;
            $data["endTime"] = $event->endTime;
            $data["teacherAccount"] = $event->teacherAccount;
            $data["teacherName"] = $event->teacherName;
            $data["folderId"] = $event->folderId;
            $data["seatNum"] = $event->seatNum;
            $data["record"] = $event->record;
            $data["live"] = $event->live;
            $data["replay"] = $event->replay;

            $this->setRequest($data);
            $result = $this->callEeoApi();

            if($result['error_info']['errno'] === 1 || $result['error_info']['errno'] === 281) {
                $event->setClassID($result['data']);
                $this->getWebcast($event,$data["courseId"],$result['data']);
            }else{
                $event->delSchedule();
                throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
            }

            ## 添加学生到课节
            $this->student($event);


        }catch (\Exception $e){
            throw $e;
        }
    }

    /**
     * 修改回放状态
     *
     */
    protected function modifyReplay(ScheduleEvent $event)
    {
        try{
            $this->setUri('setClassVideoMultiple');
            $data = $this->dataMaker();
            $data["courseId"] = $event->courseId;

            $class['classid'] = $event->classId;
            $class['record'] = $event->record;
            $class['live'] = $event->live;
            $class['replay'] = $event->replay;
            $classes[] = $class;

            $data["classJson"] = json_encode($classes);
            $this->setRequest($data);
            $result = $this->callEeoApi();

            if($result['error_info']['errno'] <> 1) {
                throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
            }
            if($result['data'][0]['errno'] <> 1){
                throw new \Exception($result['data'][0]['error'], $result['data'][0]['errno']);
            }
        }catch (\Exception $e){
            throw $e;
        }
    }
}
